#!/usr/bin/env python
# -*- encoding: utf-8 -*-
'''
@File    :   mapMgr
@Time    :   2023/2/21 16:34:26
@author  :   Eval
@Version :   1.0
@Describe:   地图管理(只负责处理地图文件,不参与数据的操作)
'''
import os,json,time
from conf.GameLogin import *
from copy import deepcopy
from conf.DiaLogResult import *
from conf.Edit.SaveJson import save as JsonSave

# 地图数据管理
class MapMgr:
    mapPath = "map\\mapFile"
    Maps = {}
    MapCache = None
    # 加载默认的新地图模板
    DefaultMap = None

    @staticmethod
    def getMapNameList():
        """获取所有的地图名称"""
        return MapMgr.Maps.keys()
    
    @staticmethod
    def getByMapName(name):
        """根据地图名称获取地图数据"""
        if MapMgr.Maps.get(name) is None:
            print_error("不存在的地图文件")
            return Result(DiaLogResult.false,"不存在的地图文件")
        MapMgr.MapCache = deepcopy(MapMgr.Maps[name])
        return Result(DiaLogResult.true,MapMgr.Maps[name])

    @staticmethod
    def resetMap(name):
        """ 从缓存中取到数据恢复当前楼层 """
        if MapMgr.Maps.get(name) is None:
            print_error("不存在的地图文件")
            return Result(DiaLogResult.false,"不存在的地图文件")
        MapMgr.Maps[name] = deepcopy(MapMgr.MapCache)
        return Result(DiaLogResult.true)

    @staticmethod
    def loadMap(parent=None):
        """加载/初始化地图数据"""
        MapMgr.Maps.clear()  # 清空
        files = os.listdir(MapMgr.mapPath)
        lenF = len(files)
        if not lenF:
            return False
        print_info(f"准备加载地图文件。")
        with open(f"conf/Edit/DefaultMap.json",encoding="utf-8") as file:
            MapMgr.DefaultMap = json.loads(file.read())
            if parent:
                time.sleep(0.02)
                parent.GameLoad.tips = "加载地图模板数据完成"
            else:
                print_info(f"加载地图模板数据完成")
        for index,f in enumerate(files):
            try:
                # 忽略加载 以 rm_ 开头的地图文件
                if f.startswith("rm_"):
                    print_info(f"-------忽略加载：{f} ")
                    continue
                if parent:
                    time.sleep(0.5)
                    parent.GameLoad.tips = f"加载地图：{f} 数据。 进度：{index+1}/{lenF}"
                else:
                    print_info(f"加载地图：{f} 数据。 进度：{index+1}/{lenF}")
                with open(f"{MapMgr.mapPath}\\{f}",encoding="utf-8") as file:
                    MapData = json.loads(file.read())
                    MapMgr.Maps[f.split(".")[0]] = MapData
                    # 将地图事件加载到缓存里,比如定义的 事件变量等..
                    # for eKey in MapData["events"]:
                    #     eValue = MapData["events"][eKey]
                        # TODO: 后续添加
                        # if len(eValue):
                        #     print_info("-"*10,eValue,indent="")

            except Exception as e:
                print_error(f"加载地图：{f} 数据失败。\错误原因：{e}")
                return Result(DiaLogResult.false,f"加载地图：{f} 数据失败。\错误原因：{e}")
        print_info(f"加载地图完成。")
        return Result(DiaLogResult.true)

    @staticmethod
    def SaveMap(map2D,fileName):
        """"生成地图文件"""
        if type(map2D) != dict:
            # print_error(f"添加地图失败。参数必须是字典类型")
            return Result(DiaLogResult.false,"添加地图失败。参数必须是字典类型")
        if fileName == "":
            print_error(f"添加地图失败。地图文件名不能为空")
            return Result(DiaLogResult.false,"添加地图失败。地图文件名不能为空")
        
        
        with open(f"{MapMgr.mapPath}\\{fileName}.json","w",encoding="utf8") as file:
            file.write(JsonSave(map2D))

        MapMgr.MapCache = deepcopy(MapMgr.Maps[fileName])
        print_info(f"保存地图:{map2D['floorName']} 成功。")
        return Result(DiaLogResult.true)

    @staticmethod
    def delMap():
        """删除地图"""
        return Result(DiaLogResult.true)
    
    @staticmethod
    def NewMap(mapName):
        """新增地图"""
        MapMgr.DefaultMap["floorName"] = mapName
        with open(f"{MapMgr.mapPath}\\{mapName}.json","w",encoding="utf8") as file:
            file.write(JsonSave(MapMgr.DefaultMap))
            
        MapMgr.Maps[mapName] = deepcopy(MapMgr.DefaultMap)
        return Result(DiaLogResult.true)